package com.xiaoc.bulldozer.controller;

import com.xc.framework.common.page.PageDto;
import com.xiaoc.bulldozer.common.ResponseCode;
import com.xiaoc.bulldozer.common.dto.UserDto;
import com.xiaoc.bulldozer.common.dto.UserRolesQueryDto;
import com.xiaoc.bulldozer.common.model.Role;
import com.xiaoc.bulldozer.common.model.User;
import com.xiaoc.bulldozer.common.model.UserRole;
import com.xiaoc.bulldozer.common.service.RoleService;
import com.xiaoc.bulldozer.common.service.UserRoleService;
import com.xiaoc.bulldozer.common.util.SecurityUtils;
import com.xiaoc.bulldozer.facade.UserFacade;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户管理
 * 
 * @author Danfo Yam
 */
@Controller
@RequestMapping(value = "/user")
public class UserController extends AdminBaseController {

    @Resource(name = "roleService")
    private RoleService roleService;
    
    @Resource(name = "userFacade")
    private UserFacade userFacade;

    @Resource(name = "userRoleService")
    private UserRoleService userRoleService;

    /**
     * 跳转新增用户页面
     */
    @RequestMapping(value = "/gotoAdd", method = RequestMethod.GET)
    public ModelAndView gotoAdd() {

        // 获取所有功能角色
        List<Role> roleList = roleService.getAllRoleList();

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("roleList", roleList);
        return renderHtml("user/user_mg.html", params);
    }

    /**
     * 跳转修改用户页面
     */
    @RequestMapping(value = "/gotoUpdate", method = RequestMethod.GET)
    public ModelAndView gotoUpdate(Integer userId) {
        
        User user = userFacade.getUserById(userId);
        user.setLoginPwd(User.DEFAULT_PASSWORD);

        // 获取用户的功能角色
        List<UserRole> userRoleList = userRoleService.getUserRoleListByUserId(userId);
        String roleIdArry = populateRoleIdStr(userRoleList);
        List<Role> roleList = roleService.getAllRoleList();

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("user", user);
        params.put("arrRoleId", roleIdArry);
        params.put("roleList", roleList);
        return renderHtml("user/user_mg.html", params);
    }
    
    /**
     * 获取用户列表
     * 
     * @throws Exception
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public ModelAndView list(UserDto userDto) {
        
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("userDto", userDto);
        params.put("roleList", roleService.getAllRoleList());
        
        Integer iCount = userFacade.queryUserCount(userDto);
        List<UserDto> userList = new ArrayList<UserDto>();
        
        if (iCount > 0) {
            userList = userFacade.queryUserList(userDto);
            Map<Integer, UserRolesQueryDto> userRolesMap = userFacade.getUserRoleMap();
            for (UserDto user : userList) {
                user.setLoginPwd(User.DEFAULT_PASSWORD);
                if(userRolesMap.get(user.getId()) != null) {
                   user.setRoleIds(userRolesMap.get(user.getId()).getRoleIds());
                   user.setRoleNames(userRolesMap.get(user.getId()).getRoleNames());
                }
            }
        }

        params.put("pageDto", new PageDto(userDto.getPage(), iCount, userDto.getPageSize()));
        params.put("userList", userList);
        return renderHtml("user/user_list.html", params);
    }

    /**
     * 创建用户
     * 
     * @throws Exception
     */
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public ModelAndView create(@RequestBody UserDto userDto) {
        
        if (StringUtils.isBlank(userDto.getLoginName())) {
            return jsonFailed(ResponseCode.PARAM_ERROR_CAN_NOT_NULL.getCode(), "用户名不能为空！");
        }
        
        if (StringUtils.isBlank(userDto.getLoginPwd())) {
            return jsonFailed(ResponseCode.PARAM_ERROR_CAN_NOT_NULL.getCode(), "密码不能为空！");
        }
        
        userDto.setLoginPwd(SecurityUtils.generatePassword(userDto.getLoginPwd()));
        userFacade.createUser(userDto);
        
        return jsonSucess();
    }

    /**
     * 更新用户
     * 
     * @throws Exception
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public ModelAndView update(@RequestBody UserDto userDto) {
        
        if (userDto.getId() == null) {
            return jsonFailed(ResponseCode.PARAM_ERROR_CAN_NOT_NULL.getCode(), "用户ID不能为空！");
        }
        
        if (StringUtils.isBlank(userDto.getLoginName())) {
            return jsonFailed(ResponseCode.PARAM_ERROR_CAN_NOT_NULL.getCode(), "用户名不能为空！");
        }
        
        if (StringUtils.isBlank(userDto.getLoginPwd())) {
            return jsonFailed(ResponseCode.PARAM_ERROR_CAN_NOT_NULL.getCode(), "密码不能为空！");
        }
        
        userFacade.updateUser(userDto);
        
        return jsonSucess();
    }

    /**
     * 删除用户
     * 
     * @throws Exception
     */
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public ModelAndView delete(@RequestBody UserDto userDto) {
        
        if (userDto.getId() == null) {
            return jsonFailed(ResponseCode.PARAM_ERROR_CAN_NOT_NULL.getCode(), "用户ID不能为空！");
        }
        
        userFacade.delUser(userDto.getId());
        
        return jsonSucess();
    }

    /**
     * @throws Exception
     */
    @RequestMapping(value = "/updateState", method = RequestMethod.POST)
    public ModelAndView updateState(@RequestBody UserDto userDto) {
        
        if (userDto.getId() == null) {
            return jsonFailed(ResponseCode.PARAM_ERROR_CAN_NOT_NULL.getCode(), "用户ID不能为空！");
        }
        
        if (userDto.getOnlineStatus() == null) {
            return jsonFailed(ResponseCode.PARAM_ERROR_CAN_NOT_NULL.getCode(), "onlineStatus");
        }
        
        Integer enableStatus = userDto.getOnlineStatus() == 0 ? User.STATUS_LOCK : User.STATUS_ENABLE;
        userFacade.lockUser(userDto.getId(), enableStatus);
        
        return jsonSucess();
    }

    /**
     * 修改密码页面
     */
    @RequestMapping(value = "/gotoEditpw", method = RequestMethod.GET)
    public ModelAndView gotoEditpw() {
        
        Map<String, Object> paramMap = new HashMap<String, Object>();
        return renderHtml("user/edit_password.html", paramMap);
    }
    
    /**
     * 更新密码
     * 
     * @throws Exception
     */
    @RequestMapping(value = "/editpw", method = RequestMethod.POST)
    public ModelAndView updatePassword(UserDto userDto) {
        
        Map<String, Object> paramMap = new HashMap<String, Object>();
        if (userDto == null || userDto.getId() == null) {
            return renderHtml("user/edit_password.html", paramMap);
        }

        // 验证旧密码
        User user = userFacade.getUserById(userDto.getId());
        if (!user.getLoginPwd().equals(SecurityUtils.generatePassword(userDto.getLoginPwd()))) {
            paramMap.put("errorMsg", "原始密码错误，请重新输入");
            return renderHtml("user/edit_password.html", paramMap);
        }
        
        //验证密码为6-14位字母+数字组合
        if (!userDto.getNewPassword().matches(User.PASSWORD_REGEX)){
            paramMap.put("errorMsg", User.PASSWORD_VALID_MSG);
            return renderHtml("user/edit_password.html", paramMap);
        }
        
        // 保存新密码
        if (!user.getLoginPwd().equals(SecurityUtils.generatePassword(userDto.getNewPassword()))) {
            userFacade.updatePassword(userDto.getId(), SecurityUtils.generatePassword(userDto.getNewPassword()));
        }
        
        paramMap.put("successMsg", "操作成功");
        return renderHtml("user/edit_password.html", paramMap);
    }

    /**
     * 组装功能角色Id数组字符串
     *
     * @param userRoleList
     *
     * @return id字符串, 如 1,2,3
     */
    private static String populateRoleIdStr(List<UserRole> userRoleList) {

        String roleIdStr = "";

        if (CollectionUtils.isEmpty(userRoleList)) {
            return roleIdStr;
        }

        for (int i = 0; i < userRoleList.size(); i++) {

            roleIdStr += userRoleList.get(i).getRoleId();

            if (i != userRoleList.size() - 1) {
                roleIdStr += ",";
            }
        }

        return roleIdStr;
    }

}
